package com.apes.hr.base.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.hr.base.model.Rank;
import com.apes.hr.base.repository.RankRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：职级
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrRankService")
public class RankService extends DomainService {
    @Autowired
    public RankRepository rankRepository;
    @Autowired
    public SequenceService sequenceService;

    public Rank save(SimpleRequest request) {
        Rank rank = request.getO(Rank.class);
        return rankRepository.saveAndFlush(rank);
    }

    public Rank update(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");
        Rank rank = rankRepository.findOne(id);
        if (rank == null)  throw new RuntimeException("职级【" + id + "】在系统中不存在。");
        if (rank.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        Rank rankDate = request.getO(Rank.class);
        return rankRepository.saveAndFlush(rankDate);
    }

    public Page<Rank> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return rankRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }
    public Page<Rank> find(SimpleRequest request) {
        return rankRepository.findAll(PageRequest.of(request.get("page"), 100) );
    }
    public Rank findOne(String id) {
        return rankRepository.findOne(id);
    }
}
